﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppAuthAdmin.AuthApiManagementServiceReference;
using Web.Framework;
using WebAppAuthAdmin.Code;
using AuthApi.Contracts;
using WebAppAuthAdmin.Code.Security;

namespace WebAppAuthAdmin.App
{
    public partial class ApplicationList : BasePage
    {
        List<WebApplicationInfo> applicationList;

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);           

            LinkButton crearContactoButton = new LinkButton();
            crearContactoButton.ID = "addApp";
            crearContactoButton.Text = "Agregar Aplicación";
            crearContactoButton.Click += new EventHandler(btnAgregarNuevo_Click);
            actionButtons.Add(crearContactoButton);                       

            base.LoadContextActions(actionButtons);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.lnkBuscar.Attributes.Add("aspnetid", this.lnkBuscar.UniqueID);
            try
            {
                if (!this.IsPostBack)
                {
                    Buscar();
                    string msgRequest = this.Request.QueryString["msg"];
                    if (!String.IsNullOrEmpty(msgRequest))
                    {
                        masterPage.ShowMessage(msgRequest, WebMessageType.Notification);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected override void ApplySecurity()
        {                        
            this.GridApplication.Columns[1].Visible = HasPermissionFor(AppSecurity.APP_DELETE);
            actionButtons.Where(a => a.ID == "addApp").Single().Visible = HasPermissionFor(AppSecurity.APP_CREATE);
        }

        private void Buscar()
        {
            applicationList = WebServiceHelper.GetApplicationList(this.txtNombre.Text);
            
            // Si la empresa es independiente de la marca, solo muestro esas aplicaciones
            var company = this.GetSingleContextCompany();
            if (company != null && company.Id == 0)
            {
                applicationList = applicationList.Where(a => a.RequiereLoginSinEmpresa).ToList();
            }
            else
            {
                applicationList = applicationList.Where(a => !a.RequiereLoginSinEmpresa).ToList();
            }

            this.GridApplication.DataSource = applicationList;
            this.GridApplication.DataBind();
        }       

        protected void GridApplication_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int appId = Convert.ToInt32(this.GridApplication.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    //this.applicationList.Where(app =
                    this.Response.Redirect(string.Format("/App/ApplicationEdit.aspx?Id={0}", appId), true);
                }
                if (e.CommandName == "eliminar")
                {
                    int appId = Convert.ToInt32(this.GridApplication.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    WebServiceHelper.DeleteApplicationById(appId);
                    Buscar();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
      
        protected void GridCustomer_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    WebApplicationInfo application = (WebApplicationInfo)e.Row.DataItem;
                    if (!HasPermissionFor(AppSecurity.APP_VIEW_ID_ + application.Id.ToString()))
                    {
                        e.Row.Visible = false;
                    }

                    if (!HasPermissionFor(AppSecurity.APP_EDIT_ID_ + application.Id.ToString()))
                    {
                        e.Row.Cells[0].Text = string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void btnAgregarNuevo_Click(object sender, EventArgs e)
        {
            try
            {
                this.Server.Transfer("/App/ApplicationEdit.aspx");
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                Buscar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }      
    }
}